const fs = require('fs');
const path = require('path');
const moment = require('moment');

interface SaveImgParams {
  file:any;
  targetPath:string;
  ctx:any;
  fileName?:string | number; 
  isAutoClear?: boolean;
}

/** 存储图片 */
export async function saveImg(params: SaveImgParams):Promise<string> {
  const { file, targetPath, ctx, fileName, isAutoClear = true } = params;
  return new Promise(async (resolve, reject) => {
    if (!file) {
      resolve('');
    }
    // 声明存放资源的路径
    let uploadDir = '';
    try {
      const f = fs.readFileSync(file.filepath);
      // 1.获取当前日期
      const day = moment(new Date()).format('YYYYMMDD');
      // 2.创建图片保存的路径
      const dir = path.join(targetPath, day);
      const date = Date.now(); // 毫秒数
      fs.mkdirSync(dir, { recursive: true });
      // 返回图片保存的路径
      uploadDir = path.join(dir, (fileName || date) + path.extname(file.filename));
      // 写入文件夹
      fs.writeFileSync(uploadDir, f);
      resolve(uploadDir);
    } catch (e) {
      console.log('error', e);
      // 清除临时文件
      reject(e);
      ctx.cleanupRequestFiles();
    }
    // 清除临时文件
    isAutoClear && ctx.cleanupRequestFiles();
  });

}
